'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import styles from '@/styles/Register.module.css';
import Link from "next/link";

// 注册表单数据接口
interface RegisterFormData {
    username: string;
    phone: string;
    code: string;
    password: string;
    confirmPassword: string;
    agreeTerms: boolean;
}

// 密码强度类型
type PasswordStrength = 'empty' | 'low' | 'medium' | 'high';

export default function Register() {
    const router = useRouter();
    const [formData, setFormData] = useState<RegisterFormData>({
        username: '',
        phone: '',
        code: '',
        password: '',
        confirmPassword: '',
        agreeTerms: false
    });
    const [countdown, setCountdown] = useState<number>(0);
    const [formErrors, setFormErrors] = useState<Record<string, string>>({});
    const [showPassword, setShowPassword] = useState<boolean>(false);
    const [passwordStrength, setPasswordStrength] = useState<PasswordStrength>('empty');

    // 处理表单输入变化
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value, type, checked } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: type === 'checkbox' ? checked : value
        }));

        // 清除对应字段的错误提示
        if (formErrors[name]) {
            setFormErrors(prev => {
                const newErrors = { ...prev };
                delete newErrors[name];
                return newErrors;
            });
        }
    };

    // 计算密码强度
    useEffect(() => {
        const password = formData.password;

        // 密码为空时
        if (!password) {
            setPasswordStrength('empty');
            return;
        }

        // 简单的密码强度检测逻辑
        let strengthScore = 0;

        // 长度检测
        if (password.length >= 8) strengthScore++;
        if (password.length >= 12) strengthScore++;

        // 字符类型检测
        if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strengthScore++; // 包含大小写字母
        if (/[0-9]/.test(password)) strengthScore++; // 包含数字
        if (/[^a-zA-Z0-9]/.test(password)) strengthScore++; // 包含特殊字符

        // 设置强度等级
        if (strengthScore <= 2) {
            setPasswordStrength('low');
        } else if (strengthScore <= 4) {
            setPasswordStrength('medium');
        } else {
            setPasswordStrength('high');
        }
    }, [formData.password]);

    // 表单验证
    const validateForm = (): boolean => {
        const errors: Record<string, string> = {};

        // 验证用户名
        if (!formData.username.trim()) {
            errors.username = '请输入用户名';
        } else if (formData.username.length < 2 || formData.username.length > 20) {
            errors.username = '用户名长度必须在2-20个字符之间';
        }

        // 验证手机号
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!formData.phone) {
            errors.phone = '请输入手机号';
        } else if (!phoneRegex.test(formData.phone)) {
            errors.phone = '请输入有效的手机号';
        }

        // 验证验证码
        if (!formData.code) {
            errors.code = '请输入验证码';
        } else if (formData.code.length !== 6) {
            errors.code = '验证码长度为6位';
        }

        // 验证密码
        if (!formData.password) {
            errors.password = '请输入密码';
        } else if (formData.password.length < 8) {
            errors.password = '密码长度不能少于8位';
        } else if (!/^(?=.*[a-zA-Z])(?=.*\d)/.test(formData.password)) {
            errors.password = '密码必须包含字母和数字';
        }

        // 验证确认密码
        if (!formData.confirmPassword) {
            errors.confirmPassword = '请确认密码';
        } else if (formData.confirmPassword !== formData.password) {
            errors.confirmPassword = '两次输入的密码不一致';
        }

        // 验证服务条款
        if (!formData.agreeTerms) {
            errors.agreeTerms = '请阅读并同意服务条款和隐私协议';
        }

        setFormErrors(errors);
        return Object.keys(errors).length === 0;
    };

    // 获取验证码
    const getVerificationCode = () => {
        // 简单验证手机号格式
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!formData.phone) {
            setFormErrors(prev => ({ ...prev, phone: '请输入手机号' }));
            return;
        }
        if (!phoneRegex.test(formData.phone)) {
            setFormErrors(prev => ({ ...prev, phone: '请输入有效的手机号' }));
            return;
        }

        // 模拟发送验证码
        toast.success('验证码已发送，请注意查收', {
            position: "top-center",
            autoClose: 2000,
            theme: 'colored',
        });

        // 开始倒计时
        setCountdown(60);
        const timer = setInterval(() => {
            setCountdown(prev => {
                if (prev <= 1) {
                    clearInterval(timer);
                    return 0;
                }
                return prev - 1;
            });
        }, 1000);

        return () => clearInterval(timer);
    };

    // 处理注册表单提交
    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        // 表单验证
        if (!validateForm()) return;

        try {
            // 模拟注册API调用
            console.log('注册数据:', formData);

            // 模拟注册成功
            toast.success('注册成功！即将跳转到登录页面', {
                position: "top-center",
                autoClose: 1500,
                theme: 'colored',
            });

            // 延迟跳转，让用户看到成功提示
            setTimeout(() => {
                router.push('/');
            }, 1500);

        } catch (error) {
            console.error('注册失败:', error);
            toast.error('注册失败，请稍后重试', {
                position: "top-center",
                autoClose: 2000,
                theme: 'colored',
            });
        }
    };

    // 处理已有账号登录跳转
    const handleLoginRedirect = () => {
        router.push('/');
    };

    // 切换密码可见性
    const togglePasswordVisibility = () => {
        setShowPassword(!showPassword);
    };

    return (
        <div className={styles.pageContainer}>
            <div className={styles.registerCard}>
                <div className={styles.cardHeader}>
                    <h1 className={styles.title}>账号注册</h1>
                    <p className={styles.subtitle}>创建账号，开启更多服务</p>
                </div>

                <form onSubmit={handleSubmit} className={styles.formContainer}>
                    {/* 用户名输入 */}
                    <div className={styles.formGroup}>
                        <label htmlFor="username" className={styles.label}>用户名</label>
                        <input
                            type="text"
                            id="username"
                            name="username"
                            className={styles.input}
                            placeholder="请设置用户名"
                            value={formData.username}
                            onChange={handleInputChange}
                            maxLength={20}
                        />
                        {formErrors.username && (
                            <p className={styles.errorMessage}>{formErrors.username}</p>
                        )}
                    </div>

                    {/* 手机号输入 */}
                    <div className={styles.formGroup}>
                        <label htmlFor="phone" className={styles.label}>手机号</label>
                        <input
                            type="tel"
                            id="phone"
                            name="phone"
                            className={styles.input}
                            placeholder="请输入手机号"
                            value={formData.phone}
                            onChange={handleInputChange}
                            maxLength={11}
                        />
                        {formErrors.phone && (
                            <p className={styles.errorMessage}>{formErrors.phone}</p>
                        )}
                    </div>

                    {/* 验证码输入 */}
                    <div className={styles.formGroup}>
                        <label htmlFor="code" className={styles.label}>验证码</label>
                        <div className={styles.codeInputContainer}>
                            <input
                                type="text"
                                id="code"
                                name="code"
                                className={`${styles.input} ${styles.codeInput}`}
                                placeholder="请输入验证码"
                                value={formData.code}
                                onChange={handleInputChange}
                                maxLength={6}
                            />
                            <button
                                type="button"
                                className={styles.getCodeBtn}
                                onClick={getVerificationCode}
                                disabled={countdown > 0 || !formData.phone}
                            >
                                {countdown > 0 ? `${countdown}s后重新获取` : '获取验证码'}
                            </button>
                        </div>
                        {formErrors.code && (
                            <p className={styles.errorMessage}>{formErrors.code}</p>
                        )}
                    </div>

                    {/* 密码输入 */}
                    <div className={styles.formGroup}>
                        <label htmlFor="password" className={styles.label}>密码</label>
                        <div className={styles.passwordInputContainer}>
                            <input
                                type={showPassword ? "text" : "password"}
                                id="password"
                                name="password"
                                className={styles.input}
                                placeholder="请设置密码（至少8位，包含字母和数字）"
                                value={formData.password}
                                onChange={handleInputChange}
                            />
                            <button
                                type="button"
                                className={styles.togglePasswordBtn}
                                onClick={togglePasswordVisibility}
                                aria-label={showPassword ? "隐藏密码" : "显示密码"}
                            >
                                <i className={showPassword ? "fa fa-eye-slash" : "fa fa-eye"}></i>
                            </button>
                        </div>

                        {/* 密码强度显示 */}
                        {passwordStrength !== 'empty' && (
                            <div className={styles.passwordStrengthContainer}>
                                <div className={styles.strengthBarContainer}>
                                    <div
                                        className={`${styles.strengthBar} ${
                                            passwordStrength === 'low' ? styles.strengthLow :
                                                passwordStrength === 'medium' ? styles.strengthMedium :
                                                    styles.strengthHigh
                                        }`}
                                        style={{
                                            width: passwordStrength === 'low' ? '33%' :
                                                passwordStrength === 'medium' ? '66%' : '100%'
                                        }}
                                    ></div>
                                </div>
                                <div className={styles.strengthText}>
                                    {passwordStrength === 'low' && '弱：密码强度较低，请增加复杂度'}
                                    {passwordStrength === 'medium' && '中：密码强度中等，可以使用'}
                                    {passwordStrength === 'high' && '强：密码强度较高，很安全'}
                                </div>
                            </div>
                        )}

                        {formErrors.password && (
                            <p className={styles.errorMessage}>{formErrors.password}</p>
                        )}
                    </div>

                    {/* 确认密码输入 */}
                    <div className={styles.formGroup}>
                        <label htmlFor="confirmPassword" className={styles.label}>确认密码</label>
                        <div className={styles.passwordInputContainer}>
                            <input
                                type={showPassword ? "text" : "password"}
                                id="confirmPassword"
                                name="confirmPassword"
                                className={styles.input}
                                placeholder="请再次输入密码"
                                value={formData.confirmPassword}
                                onChange={handleInputChange}
                            />
                            <button
                                type="button"
                                className={styles.togglePasswordBtn}
                                onClick={togglePasswordVisibility}
                                aria-label={showPassword ? "隐藏密码" : "显示密码"}
                            >
                                <i className={showPassword ? "fa fa-eye-slash" : "fa fa-eye"}></i>
                            </button>
                        </div>
                        {formErrors.confirmPassword && (
                            <p className={styles.errorMessage}>{formErrors.confirmPassword}</p>
                        )}
                    </div>

                    {/* 服务条款同意选项 */}
                    <div className={styles.termsItem}>
                        <label className={styles.termsLabel}>
                            <input
                                type="checkbox"
                                name="agreeTerms"
                                className={styles.checkbox}
                                checked={formData.agreeTerms}
                                onChange={handleInputChange}
                            />
                            <span>
                                我已阅读并同意
                                <Link href="#" className={styles.link} target="_blank" rel="noopener noreferrer">
                                    《服务条款》
                                </Link>
                                和
                                <Link href="#" className={styles.link} target="_blank" rel="noopener noreferrer">
                                    《隐私协议》
                                </Link>
                            </span>
                        </label>
                        {formErrors.agreeTerms && (
                            <p className={styles.errorMessage}>{formErrors.agreeTerms}</p>
                        )}
                    </div>

                    {/* 注册按钮 */}
                    <button
                        type="submit"
                        className={styles.registerBtn}
                        disabled={!formData.agreeTerms}
                    >
                        注册账号
                    </button>

                    {/* 已有账号登录链接 */}
                    <div className={styles.loginRedirect}>
                        已有账号？
                        <button
                            type="button"
                            className={styles.backToLoginBtn}
                            onClick={handleLoginRedirect}
                        >
                            立即登录
                        </button>
                    </div>
                </form>
            </div>

            {/* 提示框容器 */}
            <ToastContainer />
        </div>
    );
}